var api = require('../../../utils/api.js')
var $ = require('../../../utils/util.js')
var regeneratorRuntime = require('../../../utils/runtime.js')
var app = getApp()
var Store = app.Store 

Page({
  data: {
    basic:{
      ticketType:'1',
      areaName:'', 
      condition:'',
      areaId:'', 
      workLeader:'',
      workLeaderId:'',
      teamName:'',
      teamId:'',
      teamMemers:[''],
      teamMemerIds:[''],
      workNum:'',
      deptId:'',
      deptName:'',
      stationName:'',
      stationId:'',
      deviceName:'',
      deviceId:'',
      switchName:'',
      switchId:'',
      workAddr:'',
      task:'',
      content:'',
      startTime:'',
      endTime:'',
      ticketNumber:'',
      isDoubleSigned:0,
      status:''
    },
    saveFlag:false,
    measures:[],
    dateNum:'',
    hasMesure:false,
    issuer:'',
    issuerId:'',
    issuer2:'',
    issuerId2:'',
    info:'',
    isShowTime: false, // 是否显示时间弹框
    isShowTime2: false, // 是否显示时间弹框
    company: '', // 企业用户
    company_id: '', // 企业id
    responsibleImg: 'https://img.yzcdn.cn/vant/cat.jpeg', // 签发人签字
    timeType:'',//选择时间类型
    submit: '', // 保存0；提交1 
    type: 'add', // 类型
  },
  onLoad: function (options) { 
    console.log(options.hasMesure)
    this.setData({dateNum:new Date().getTime(),hasMesure:options.hasMesure,"basic.ticketType": options.ticketType})
    if ('ticketNumber' in options){ 
      this.setData({
        "basic.ticketNumber": options.ticketNumber, 
      })
      api.$get(api.workTicket.workTickInfo+options.ticketNumber).then((res) => {
        this.setData({
          basic:res.data,
          'basic.deptName':res.data.relatedInformation.projectName,
          'basic.deptId':res.data.relatedInformation.projectDeptId,
          'basic.areaName':res.data.relatedInformation.areaName,
          'basic.areaId':res.data.relatedInformation.areaId,
          'basic.teamName':res.data.relatedInformation.teamName,
          'basic.teamId':res.data.relatedInformation.teamId,
          'basic.teamMemers':res.data.relatedInformation.teamMemberNameList,
          'basic.teamMemerIds':res.data.relatedInformation.teamMemberIdList,
          'basic.workNum':res.data.relatedInformation.teamMemberNumber,
          'basic.deviceName':res.data.relatedInformation.deviceName,
          'basic.deviceId':res.data.relatedInformation.deviceId,
          'basic.switchName':res.data.relatedInformation.switchName,
          'basic.switchId':res.data.relatedInformation.switchId,
          type:'edit',
        })
      })
    }else{
      console.log(wx.getStorageSync('user_name'))
      this.setData({
        'basic.workLeader':wx.getStorageSync('user_name'),
        'basic.workLeaderId':wx.getStorageSync('user_id'),
        'type':'add'
      })
    }
  },

  onShow(){
    var form = Store.getState().formInfor.form
    var key = form.key
    if (!form.selected) return
    switch (key) {
      case 'selectTickDpt': // 获取部门信息  
        this.setData({
          "basic.areaName": form.selected.areaName,
          "basic.areaId": form.selected.areaId,
          "basic.teamName": '',
          "basic.teamId":'',
        })
        break
      case 'selectWorkTeam': // 获取班组  
        this.setData({
          "basic.teamName": form.selected.teamName,
          "basic.teamId": form.selected.teamId,
          "basic.teamMemers": '',
          "basic.teamMemerIds":'',
        })
        break
      case 'selectWorkPeops':
        this.setData({
          "basic.teamMemers": form.selected.map((item)=>item.userName),
          "basic.teamMemerIds":form.selected.map((item)=>item.userId),
          "basic.workNum":form.selected.map((item)=>item.userName).find((item)=>item==this.data.basic.workLeader?form.selected.map((item)=>item.userName).length:form.selected.map((item)=>item.userName).length+1)
        })
        break
      case 'selectWorkProject'://获取项目
        this.setData({
          "basic.deptName": form.selected.label,
          "basic.deptId":form.selected.id,
          "basic.stationName": '',
          "basic.stationId": '',
        })
        break
      case 'selectWorkStation': // 获取厂站  
        this.setData({
          "basic.stationName": form.selected.label,
          "basic.stationId": form.selected.station,
          "basic.deviceName": '',
          "basic.deviceId": '',
        })
        this.getTickNumber(form.selected.station)
        break
      case 'selectWorkDevice': // 获取设备  
        this.setData({
          "basic.deviceName": form.selected.label,
          "basic.deviceId": form.selected.id,
          "basic.task":this.data.basic.stationName+form.selected.label,
          "basic.content":this.data.basic.stationName+form.selected.label,
          "basic.switchName": '',
          "basic.switchId": '',
        });
        break
      case 'selectWorkSwitch': // 获取开关  
        this.setData({
          "basic.switchName": form.selected.label,
          "basic.switchId": form.selected.id,
        })
        break
      case 'selectIssuer': // 获取签发人  
        this.setData({
          issuer: form.selected.userName,
          issuerId: form.selected.userId,
        })
        break 
      case 'selectIssuer2': // 获取签发人  
        this.setData({
          issuer2: form.selected.userName,
          issuerId2: form.selected.userId,
        })
        break 
      case 'workSign': // 获取签发人签名  
        this.setData({
          responsibleImg: form.selected,
        })
        break 
        
    }
  },
  getTickNumber(stationId){
    if(this.data.type=='add'){
      api.$get(api.workTicket.requestTicketNumber,{stationId:stationId}).then((res) => {
        this.setData({'basic.ticketNumber':res.data.ticketNumber})
      })
    }
    
  },
  selectDepartment() {
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'selectTickDpt', // 后台要的更改字段 
        type: 1, // 表单类型 1： radio  2：select
        config: {
        },
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)  
  },

  selectWorkTeam() { // 选班组
    if(this.data.basic.areaId==''){
      $.toast("请先选择项目")
    }else{
      if(this.data.basic.depart== ''){
        $.toast('请选择所属部门')
      }else {
        Store.dispatch({
          type: 'SET_FROM',
          form: {
            key: 'selectWorkTeam', // 后台要的更改字段 
            type: 1, // 表单类型 1： radio  2：select
            config: {
              // depart: this.data.basic.depart, 
              areaId: this.data.basic.areaId ,
            },
          },
        })
        $.linkurl(`/pages/main/chooseForm/chooseForm`)
      } 
    }
  },
  selectWorkPeops() { // 选工作人员
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
    }else{
      Store.dispatch({
        type: 'SET_FROM',
        form: {
          key: 'selectWorkPeops', // 后台要的更改字段 
          type:2, // 表单类型 1： radio  2：select
          config: {
            dataType:'object',
            teamId: this.data.basic.teamId ,
          },
        },
      })
      $.linkurl(`/pages/main/chooseForm/chooseForm`)
    }
  },
  changeWorkNum(){
    var that=this
    wx.showModal({
      title: '参加人数',
      editable: true,
      placeholderText:'请输入数字',
      success (res) {
        if (res.confirm) {
          if(isNaN(res.content)){
            $.toast("请输入阿拉伯数字");
            
          }else{
            that.setData({
              "basic.workNum":res.content
            })
          }
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  selectWorkProject(){
    if (this.data.type!='add'&&this.data.basic.status==6) {
      $.toast('已生成票号无法修改，如需换站请重新新增工作票')
      return false
    }
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'selectWorkProject', // 后台要的更改字段 
        type: 1, // 表单类型 1： radio  2：select
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)
  },
  selectWorkStation(){
    if (this.data.type!='add'&&this.data.basic.status==6) {
      $.toast('已生成票号无法修改，如需换站请重新新增工作票')
      return false
    }
    if (this.data.basic.deptName == '') {
      $.toast('请选择厂站')
    }
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'selectWorkStation', // 后台要的更改字段 
        type: 1, // 表单类型 1： radio  2：select
        config: {
          parentId: this.data.basic.deptId
        },
      },
    })
    $.linkurl(`/pages/main/chooseForm/chooseForm`)
  },
  selectWorkDevice (e) { // 根据厂站获取设备列表 
    if (this.data.type!='add'&&this.data.basic.status==6) {
      $.toast('已生成票号无法修改，如需换站请重新新增工作票')
      return false
    }
    if (this.data.basic.stationName == '') {
      $.toast('请选择厂站')
    } else {
      Store.dispatch({
        type: 'SET_FROM',
        form: {
          key: 'selectWorkDevice', // 后台要的更改字段 
          type: 1, // 表单类型 1： radio  2：select
          config: {
            stationId: this.data.basic.stationId
          },
        },
      })
      $.linkurl(`/pages/main/chooseForm/chooseForm`)
      
    } 
  },
  selectWorkSwitch (e) { // 获取开关列表 
    if (this.data.basic.deviceName == '') {
      $.toast('请选择设备')
    } else {
      Store.dispatch({
        type: 'SET_FROM',
        form: {
          key: 'selectWorkSwitch', // 后台要的更改字段 
          type: 1, // 表单类型 1： radio  2：select
          config: {
            deviceId: this.data.basic.deviceId
          },
        },
      })
      $.linkurl(`/pages/main/chooseForm/chooseForm`)
      
    } 
  },
  changeWorkAddr(e){
    console.log(e.detail.value)
    this.setData({'basic.task':e.detail.value})
  },
  changeWorkContent(e){
    
    this.setData({'basic.content':e.detail.value})
  },
  changeWorkCondition(e){
    this.setData({'basic.condition':e.detail.value})
  },
  getSignType(){
    var that=this 
    wx.showActionSheet({
      itemList: ['单签', '双签'],
      success (res) {
        that.setData({
          "basic.isDoubleSigned":res.tapIndex
        })
      },
      fail (res) {
        console.log(res.errMsg)
      }
    })
  },
  openTimeHandle(e) { // 打开时间弹框
    const {item}=$.detail(e)
    this.setData({
      timeType:item
    })
    if(this.data.info.submit=='1'){
      $.toast("已提交无法修改")
  }else{
    if(item=='startTime'||item=='pzStartTime'){
      this.setData({
        isShowTime: true
      })
    }else if((item=='endTime'&&this.data.basic.startTime!='')||item=='pzEndTime'&&this.data.pzEndTime!=''){
      this.setData({
        isShowTime2: true
      })
    }else{
      $.toast("请先选择开始时间")
    }
      
    }
  },
  timeConfirmHandle(e) { // 时间组件传出来的数据
    var { time, key } = e.detail

    this.setData({
      [key]: time
    })
  
    console.log(time, key)
  },
  
  bigSign(e){
    const {img}=$.detail(e)
    wx.previewImage({
      current: '', // 当前显示图片的链接，不填则默认为urls的第一张
      urls: [img, 'https://example.com/2.jpg'] // 需要预览的图片链接列表
    })
  },
  responsibleSign(e){  
    Store.dispatch({
      type: 'SET_FROM',
      form: {
        key: 'workSign', 
      },
    })
    $.linkurl(`/pages/components/signatrue/signAture`) 
  },
  cancelMake(){
    $.linkurl(``,'back')
  },
  subTicket(){
    if(this.data.basic.deptName==''||this.data.basic.teamName==''||this.data.basic.teamMemers[0]==''||this.data.basic.deviceName==''||this.data.basic.content==''||this.data.basic.startTime==""||this.data.basic.endTime==""){
      $.toast('请输入完整的必填项信息')
      return false
    }
    (this.data.type=='add'?api.$post(api.workTicket.addTicketWork,{...this.data.basic,deviceId:Boolean(this.data.basic.switchId)?this.data.basic.switchId:this.data.basic.deviceId,deviceName:Boolean(this.data.basic.switchId)?this.data.basic.switchName:this.data.basic.deviceName}):api.$put(api.workTicket.editTicketWork,{...this.data.basic,deviceId:Boolean(this.data.basic.switchId)?this.data.basic.switchId:this.data.basic.deviceId,deviceName:Boolean(this.data.basic.switchId)?this.data.basic.switchName:this.data.basic.deviceName})).then((res) => {
      if(res.code==200){
        api.$post(api.workTicket.addTempTeam,{
          ticketNumber:this.data.basic.ticketNumber,
          teamName:this.data.basic.teamName,
          teamLeaderId:this.data.basic.workLeaderId,
          teamMemerIds:this.data.basic.teamMemerIds.join(','),
          areaId:this.data.basic.areaId,
        }).then((res) => {
          console.log('res1',res)
          if(res.code==200){
            $.toast('保存成功')
            $.linkurl(`/pages/workTicket/workTicketMore/workTicketMore?deviceId=${this.data.basic.deviceId}&ticketNumber=${this.data.basic.ticketNumber}&deptId=${this.data.basic.deptId}&signType=${this.data.basic.isDoubleSigned}&type=${this.data.type}&hasMesure=${this.data.hasMesure}&ticketType=${this.data.basic.ticketType}`,'redirect')
          }
        })
        
      }
    })
    
    
  },
})